package com.example.thegreatwall.common;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
public class AliOSSUtil {
    //阿里云的服务地址
    private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    //id号
    private String accessKeyId = "LTAI5tAXDVRDHfUMi3UpdkG9";
    //秘钥
    private String accessKeySecret = "g94g0KYmQDFlHg2WMbEUT7p4nYNlhF";
    //用户名
    private String bucketName = "dengqirong123";

    /**
     *
     * @param file 要上传的文件
     * @return 文件上传后所存放的地址
     */
    public String upload(MultipartFile file) throws IOException {
        //取得上传文件的输入流
        InputStream inputStream = file.getInputStream();
        //得到文件名字
        String originalFilename = file.getOriginalFilename();
        //我将输出文件名
        System.out.println("originalFilename = " + originalFilename);
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        //uuid 全球唯一
        String fileName= UUID.randomUUID().toString() + suffix;
        //得到阿里上传文件的客户
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        //调用上传的方法
        oss.putObject(bucketName, fileName, inputStream);
        //关闭
        oss.shutdown();
        //拼接好存放的地址
        String fileUrl="";
        fileUrl=endpoint.substring(0,8)+bucketName+"."+endpoint.substring(8)+"/"+fileName;
        System.out.println("fileUrl = " + fileUrl);
        return fileUrl;
    }

}
